<template>
  <a-modal v-model:open="visible" title="修改密码" :confirmLoading="loading" @ok="handleSubmit" @cancel="handleCancel" :width="400" :maskClosable="false">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" @finish="onFinish">
      <a-form-item label="原密码" name="oldPassword">
        <a-input-password v-model:value="formData.oldPassword" placeholder="请输入原密码" size="large" />
      </a-form-item>

      <a-form-item label="新密码" name="newPassword">
        <a-input-password v-model:value="formData.newPassword" placeholder="请输入新密码（6-20位）" size="large" />
      </a-form-item>

      <a-form-item label="确认新密码" name="confirmPassword">
        <a-input-password v-model:value="formData.confirmPassword" placeholder="请再次输入新密码" size="large" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import { changePassword } from '@/utils/api'

// 定义 props 和 emits
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const visible = ref(props.visible)
const loading = ref(false)
const formRef = ref()

// 表单数据
const formData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20位之间', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/,
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value && value !== formData.newPassword) {
          return Promise.reject(new Error('两次输入的密码不一致'))
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 监听 props 变化
watch(
  () => props.visible,
  (newVal) => {
    visible.value = newVal
  }
)

// 监听内部 visible 变化
watch(visible, (newVal) => {
  emit('update:visible', newVal)
})

// 处理表单提交
const handleSubmit = () => {
  formRef.value
    ?.validate()
    .then(() => {
      onFinish()
    })
    .catch(() => {
      // 验证失败，不做任何操作
    })
}

// 表单验证通过后的处理
const onFinish = async () => {
  loading.value = true

  try {
    await changePassword({
      oldPassword: formData.oldPassword,
      newPassword: formData.newPassword
    })

    message.success('密码修改成功')
    emit('success')
    handleCancel()
  } catch (error) {
    console.error('修改密码失败:', error)
    message.error(error.message || '修改密码失败')
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  visible.value = false
  // 清空表单
  formData.oldPassword = ''
  formData.newPassword = ''
  formData.confirmPassword = ''
  // 清除验证状态
  formRef.value?.resetFields()
}
</script>

<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 20px;
}

:deep(.ant-input-password) {
  border-radius: 6px;
}
</style>
